package com.suma.android.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.Window;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.suma.android.constant.Constant;
import com.suma.android.update.UpdateManager;
import com.suma.android.util.JSONUtil;
import com.suma.android.util.RtmpUrl;
import com.suma.android.util.VideoConfig;

public class MainActivity extends Activity {
	private WebView webview;
	private RtmpUrl jsInterface;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		webview = (WebView) findViewById(R.id.webView1);
		jsInterface = new RtmpUrl();
		WebSettings webSettings = webview.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setPluginsEnabled(true);
		webSettings.setAllowFileAccess(true);
		webSettings.setBuiltInZoomControls(true);
		webSettings.setUseWideViewPort(true);
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
		webSettings.setUserAgentString(webSettings.getUserAgentString()+"(APP)");
		webview.loadUrl(Constant.PORTAL_URL);
		webview.setWebViewClient(new DefaultWebViewClient());
		webview.setWebChromeClient(new DefaultWebChromeClient());
		// webview.addJavascriptInterface(jsInterface, jsInterface.JSNAME);
		// 24小时之内checkUpdate过，则不再checkUpdate
		SharedPreferences sp = getSharedPreferences(Constant.SHARE_PREF_NAME,
				Context.MODE_PRIVATE);
		long checkDate = sp.getLong(Constant.CHECK_VERSION_KEY, 0L);
		if ((System.currentTimeMillis() - checkDate) > 24 * 3600 * 1000L) {
			new UpdateManager(this).update();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (webview.canGoBack()) {
				webview.goBack();
				return true;
			} else {
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage(R.string.info_confirm_quit)
						.setCancelable(false)
						.setPositiveButton(R.string.confirm,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										MainActivity.this.finish();
									}
								})
						.setNegativeButton(R.string.cancle,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
									}
								});
				AlertDialog alert = builder.create();
				alert.show();
				return true;
			}
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	protected void onDestroy() {
		webview.clearCache(true);
		super.onDestroy();
	}

	private class DefaultWebViewClient extends WebViewClient {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, final String url) {
			if (url.startsWith("video:")) {
				String path = url.substring(6);
				Log.i(ACTIVITY_SERVICE, path);
				VideoConfig config = JSONUtil.parse(path);
				if (config != null && config.getUrl() != null
						&& !"".equals(config.getUrl())) {
					Intent intent = new Intent(MainActivity.this,
							PlayerActivity.class);
					intent.putExtra("url", config);
					// if(config.getUrl().startsWith("rtmp://")){
					// int p = path.lastIndexOf("/");
					// jsInterface.setStreamer(path.substring(0, p + 1));
					// jsInterface.setFile(path.substring(p + 1));
					// view.loadUrl("file:///android_asset/vod.html");
					// } else {
					MainActivity.this.startActivity(intent);
					// }
				} else {
					Toast.makeText(MainActivity.this,
							R.string.error_url_invalid, Toast.LENGTH_LONG)
							.show();
				}
			} else {
				view.loadUrl(url);
			}
			return true;
		}
	}

	private class DefaultWebChromeClient extends WebChromeClient {

		@Override
		public boolean onJsAlert(WebView view, String url, String message,
				final JsResult result) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					MainActivity.this);
			builder.setMessage(message)
					.setCancelable(false)
					.setPositiveButton(R.string.confirm,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									result.confirm();
								}
							});
			AlertDialog alert = builder.create();
			alert.show();
			return true;
		}

		@Override
		public boolean onJsConfirm(WebView view, String url, String message,
				final JsResult result) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					MainActivity.this);
			builder.setMessage(message)
					.setCancelable(false)
					.setPositiveButton(R.string.confirm,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									result.confirm();
								}
							})
					.setNegativeButton(R.string.cancle,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									result.cancel();
								}
							});
			AlertDialog alert = builder.create();
			alert.show();
			return true;
		}
		
	}
}
